package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.convert.AppConvert;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.mapper.AppMapper;
import com.yh.merchant.api.Service.IAppService;
import com.yh.merchant.api.dto.AppDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class AppServiceImpl implements IAppService  {

    @Autowired
    AppMapper appMapper;

    /**
     * 商户创建应用
     * @param appDTO
     * @return
     */
    @Override
    public AppDTO crratApp(AppDTO appDTO)  throws BusinessException {
        //1.非空校验
        if (StringUtils.isEmpty(appDTO.getAppName())){
            throw new BusinessException(CommonErrorCode.E_200001);
        }
        if (appDTO.getMerchantId() == null){
            throw new BusinessException(CommonErrorCode.E_200002);
        }
        //2.对象转换
        App app = AppConvert.INSTANCE.dto2Entity(appDTO);
        //3.保存数据 AppId需要自己生成 UUId
        app.setAppId(RandomUuidUtil.getUUID());
        appMapper.insert(app);
        return AppConvert.INSTANCE.entity2Dto(app);
    }

    @Override
    public AppDTO myapp(String appId) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(App::getAppId,appId);
        App app = appMapper.selectOne(queryWrapper);
        return AppConvert.INSTANCE.entity2Dto(app);
    }

    @Override
    public List<AppDTO> myApps(Long merchantId) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(App::getMerchantId,merchantId);
        List<App> apps = appMapper.selectList(queryWrapper);

        return AppConvert.INSTANCE.listEntity2ListDto(apps);
    }
}
